package medical_dept_dao

import (
	"gorm.io/gorm/clause"
	"jjqzplucky.site/sz-core/internal/models"
	medicalDeptModel "jjqzplucky.site/sz-core/internal/models/medical_dept"
	"jjqzplucky.site/sz-core/pkg/utils"
)

func SelectDeptAndSub() ([]medicalDeptModel.MedicalDept, error) {
	db := models.DB
	model := medicalDeptModel.MedicalDept{}
	var depts []medicalDeptModel.MedicalDept
	if err := db.Model(&model).Preload("Children").Find(&depts).Error; err != nil {
		return nil, err
	}
	return depts, nil
}

func Create(model medicalDeptModel.MedicalDept) error {
	db := models.DB
	if err := db.Create(&model).Error; err != nil {
		return err
	}
	return nil
}

func Update(model medicalDeptModel.MedicalDept) error {
	db := models.DB
	if err := db.Omit("create_time").Save(&model).Error; err != nil {
		return err
	}
	return nil
}

func Delete(model medicalDeptModel.MedicalDept) error {
	db := models.DB
	if err := db.Delete(&model).Error; err != nil {
		return err
	}
	return nil
}

func Page(param medicalDeptModel.PageQuery) utils.PageResult {
	query := models.DB.Model(&medicalDeptModel.MedicalDept{})
	var count int64
	if param.Name != nil {
		query = query.Clauses(clause.Like{Column: "name", Value: "%" + *param.Name + "%"})
	}
	if param.Outpatient != nil {
		query = query.Where("outpatient = ?", param.Outpatient)
	}
	if param.Recommended != nil {
		query = query.Where("recommended = ?", param.Outpatient)
	}
	if param.Page != 0 {
		query = query.Offset((param.Page - 1) * param.PageSize)
	} else {
		query = query.Offset(0)
	}
	if param.PageSize != 0 {
		query = query.Limit(param.PageSize)
	} else {
		query = query.Limit(10)
	}

	var list []medicalDeptModel.MedicalDept
	query.Count(&count).Find(&list)
	return utils.PageResult{
		List:     list,
		Page:     param.Page,
		PageSize: param.PageSize,
		Total:    int64(count),
	}
}

func PageWithSimple(param models.PageParam) utils.PageResult {
	var list []medicalDeptModel.SimpleMedical
	var count int64
	models.DB.Model(&medicalDeptModel.MedicalDept{}).Offset((param.Page - 1) * param.PageSize).Limit(param.PageSize).Count(&count).Scan(&list)
	return utils.PageResult{
		List:     list,
		Page:     param.Page,
		PageSize: param.PageSize,
		Total:    count,
	}
}
